package com.feige.filter;

import com.feige.entity.SecurityUser;
import com.feige.result.AjaxResult;
import com.feige.utils.jwt.JwtUtils;
import com.feige.utils.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;
import com.feige.utils.http.ResponseUtil;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

@Slf4j
public class TokenAuthenticationFilter extends BasicAuthenticationFilter {

    private RedisUtils redisUtils;

    public TokenAuthenticationFilter(AuthenticationManager authManager,RedisUtils redisUtils) {
        super(authManager);
        this.redisUtils = redisUtils;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        log.info("================="+req.getRequestURI());
        if(!req.getRequestURI().contains("admin")) {
            chain.doFilter(req, res);
            return;
        }

        UsernamePasswordAuthenticationToken authentication = null;
        try {
            authentication = getAuthentication(req);
        } catch (Exception e) {
            ResponseUtil.out(res,AjaxResult.error());
        }

        if (authentication != null) {
            //存储当前认证信息
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } else {
            ResponseUtil.out(res, AjaxResult.error());
        }
        chain.doFilter(req, res);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {

        String token = request.getHeader("token");
        String username = JwtUtils.getUsernameAndNumFromToken(token);
        if (!StringUtils.isEmpty(username)){
            SecurityUser securityUser = (SecurityUser) redisUtils.get(username);
            System.out.println(securityUser);
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            for (String permission : securityUser.getPermissions()) {
                if(StringUtils.isEmpty(permission)) continue;
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
                authorities.add(authority);
            }
            //参数：当前用户，登录凭证token，权限
            return new UsernamePasswordAuthenticationToken(username, token, authorities);
        }
        return null;
    }
}
